<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RabbitMQ 队列监控</title>
    <style>
        :root {
            --bg-primary: #121212;
            --bg-secondary: #1e1e1e;
            --bg-card: #252526;
            --bg-modal: #2d2d30;
            --text-primary: #e0e0e0;
            --text-secondary: #a0a0a0;
            --accent-primary: #4caf50;
            --accent-secondary: #2196f3;
            --accent-warning: #ff9800;
            --accent-danger: #f44336;
            --accent-info: #3f51b5;
            --border-color: #3c3c3c;
            --hover-bg: #333333;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--bg-primary);
            color: var(--text-primary);
            line-height: 1.6;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: var(--bg-card);
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        }

        h1 {
            color: var(--accent-primary);
            text-align: center;
            margin-bottom: 25px;
            font-size: 28px;
            font-weight: 600;
        }

        .controls {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
            justify-content: center;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }

        .btn-primary {
            background-color: var(--accent-primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: #43a047;
        }

        .btn-secondary {
            background-color: var(--accent-secondary);
            color: white;
        }

        .btn-secondary:hover {
            background-color: #1e88e5;
        }

        .btn-warning {
            background-color: var(--accent-warning);
            color: white;
        }

        .btn-warning:hover {
            background-color: #ef6c00;
        }

        .btn-danger {
            background-color: var(--accent-danger);
            color: white;
        }

        .btn-danger:hover {
            background-color: #e53935;
        }

        .btn-info {
            background-color: var(--accent-info);
            color: white;
        }

        .btn-info:hover {
            background-color: #303f9f;
        }

        .nav-link {
            background-color: var(--accent-secondary);
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .nav-link:hover {
            background-color: #1e88e5;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }

        table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        }

        th {
            background-color: var(--bg-secondary);
            color: var(--accent-primary);
            font-weight: 600;
            text-align: left;
            padding: 16px 20px;
        }

        td {
            padding: 16px 20px;
            border-bottom: 1px solid var(--border-color);
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover {
            background-color: var(--hover-bg);
        }

        .queue-name {
            color: var(--accent-secondary);
            cursor: pointer;
            font-weight: 500;
            transition: color 0.2s;
        }

        .queue-name:hover {
            color: #64b5f6;
            text-decoration: underline;
        }

        .message-count {
            font-weight: 700;
            color: var(--accent-warning);
            cursor: pointer;
            transition: color 0.2s;
        }

        .message-count:hover {
            color: #ffa726;
            text-decoration: underline;
        }

        .consumer-count {
            font-weight: 700;
            color: var(--accent-primary);
        }

        .loading {
            text-align: center;
            color: var(--text-secondary);
            font-style: italic;
            padding: 30px;
        }

        .error {
            color: #ff8a80;
            background-color: rgba(244, 67, 54, 0.15);
            padding: 15px;
            border-radius: 6px;
            margin: 15px 0;
            border-left: 4px solid var(--accent-danger);
        }

        .success {
            color: #a5d6a7;
            background-color: rgba(76, 175, 80, 0.15);
            padding: 15px;
            border-radius: 6px;
            margin: 15px 0;
            border-left: 4px solid var(--accent-primary);
        }

        input[type="text"], input[type="password"], input[type="number"] {
            padding: 10px 15px;
            border-radius: 6px;
            border: 1px solid var(--border-color);
            background-color: var(--bg-secondary);
            color: var(--text-primary);
            font-size: 15px;
            width: 100%;
            box-sizing: border-box;
        }

        input:focus {
            outline: none;
            border-color: var(--accent-primary);
            box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(5px);
        }

        .modal-content {
            background-color: var(--bg-modal);
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 800px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
            border: 1px solid var(--border-color);
            position: relative;
        }

        .close {
            color: var(--text-secondary);
            float: right;
            font-size: 32px;
            font-weight: bold;
            cursor: pointer;
            position: absolute;
            top: 15px;
            right: 25px;
            transition: color 0.2s;
        }

        .close:hover {
            color: var(--text-primary);
        }

        .config-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 20px;
        }

        @media (max-width: 768px) {
            .config-form {
                grid-template-columns: 1fr;
            }
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-primary);
        }

        .message-item {
            border: 1px solid var(--border-color);
            padding: 15px;
            margin: 15px 0;
            background-color: var(--bg-secondary);
            border-radius: 6px;
            word-break: break-all;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 15px;
        }

        .message-content {
            flex: 1;
        }

        .message-header {
            font-weight: 700;
            margin-bottom: 10px;
            color: var(--accent-secondary);
        }

        .delete-btn {
            background-color: var(--accent-danger);
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            height: fit-content;
            transition: background-color 0.2s;
            flex-shrink: 0;
        }

        .delete-btn:hover {
            background-color: #e53935;
        }

        .refresh-btn {
            background-color: var(--accent-primary);
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            height: fit-content;
            transition: background-color 0.2s;
            flex-shrink: 0;
        }

        .refresh-btn:hover {
            background-color: #43a047;
        }

        .remove-btn {
            background-color: var(--accent-danger);
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            height: fit-content;
            transition: background-color 0.2s;
            flex-shrink: 0;
        }

        .remove-btn:hover {
            background-color: #e53935;
        }

        .card {
            background-color: var(--bg-card);
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .card-title {
            font-size: 20px;
            margin-bottom: 20px;
            color: var(--accent-primary);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-secondary);
        }

        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📬 消息队列管理面板</h1>
        <div class="controls">
            <div class="nav-buttons">
                <button class="btn btn-primary" onclick="loadQueues()">🔄 刷新队列信息</button>
                <button class="btn" onclick="showConfigModal()">⚙️ 配置连接</button>
                <button class="btn btn-warning" onclick="window.location.href='/redis.html'">🔄 切换到 Redis 管理</button>
                <button class="btn" onclick="window.location.href='/file.html'">📁 文件查看器</button>
            </div>
        </div>

        <div id="statusMessage"></div>
        
        <div id="queueList">
            <p class="loading">⏳ 正在加载队列信息...</p>
        </div>
    </div>

    <!-- 配置模态框 -->
    <div id="configModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeConfigModal()">&times;</span>
            <h2>⚙️ RabbitMQ 连接配置</h2>
            <div id="configMessage"></div>
            <form id="configForm" class="config-form">
                <div class="form-group">
                    <label for="host">🖥️ 主机地址:</label>
                    <input type="text" id="host" value="192.168.11.199" required>
                </div>
                
                <div class="form-group">
                    <label for="port">🔌 端口:</label>
                    <input type="number" id="port" value="5672" required>
                </div>
                
                <div class="form-group">
                    <label for="username">👤 用户名:</label>
                    <input type="text" id="username" value="test" required>
                </div>
                
                <div class="form-group">
                    <label for="password">🔒 密码:</label>
                    <input type="password" id="password" value="test" required>
                </div>
                
                <div class="form-group">
                    <label for="virtualHost">🔗 Virtual Host:</label>
                    <input type="text" id="virtualHost" value="/" required>
                </div>
                
                <div style="grid-column: span 2; text-align: center; margin-top: 10px;">
                    <button type="button" class="btn btn-primary" onclick="saveConfig()">💾 保存配置</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 消息内容模态框 -->
    <div id="messageModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeMessageModal()">&times;</span>
            <h2>💬 队列 "<span id="modalQueueName"></span>" 中的消息</h2>
            <div id="messageContent">
                <p class="loading">⏳ 正在加载消息...</p>
            </div>
        </div>
    </div>

    <script>
        // 页面加载完成后自动加载队列信息
        window.onload = function() {
            loadQueues();
        };

        // 显示配置模态框
        function showConfigModal() {
            document.getElementById('configModal').style.display = 'block';
        }

        // 关闭配置模态框
        function closeConfigModal() {
            document.getElementById('configModal').style.display = 'none';
        }

        // 关闭消息模态框当用户点击×按钮
        function closeMessageModal() {
            document.getElementById('messageModal').style.display = 'none';
        }

        // 关闭模态框当用户点击模态框外部
        window.onclick = function(event) {
            var configModal = document.getElementById('configModal');
            var messageModal = document.getElementById('messageModal');
            if (event.target == configModal) {
                configModal.style.display = 'none';
            }
            if (event.target == messageModal) {
                messageModal.style.display = 'none';
            }
        }

        // 保存配置
        function saveConfig() {
            const host = document.getElementById('host').value;
            const port = document.getElementById('port').value;
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const virtualHost = document.getElementById('virtualHost').value;
            
            // 发送配置到后端
            fetch('/api/rabbitmq/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `host=${encodeURIComponent(host)}&port=${encodeURIComponent(port)}&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&virtualHost=${encodeURIComponent(virtualHost)}`
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById('configMessage').innerHTML = '<div class="success">✅ ' + data + '</div>';
                setTimeout(() => {
                    document.getElementById('configModal').style.display = 'none';
                    document.getElementById('configMessage').innerHTML = '';
                }, 1000);
            })
            .catch(error => {
                document.getElementById('configMessage').innerHTML = '<div class="error">❌ 配置保存失败: ' + error + '</div>';
            });
        }

        // 加载所有队列信息
        function loadQueues() {
            document.getElementById('queueList').innerHTML = '<p class="loading">⏳ 正在加载队列信息...</p>';
            
            // 由于RabbitMQ协议限制，无法通过AMQP协议直接获取所有队列列表
            // 实际项目中应通过RabbitMQ Management API获取
            document.getElementById('queueList').innerHTML = `
                <div class="error">
                    <p>⚠️ 注意：由于AMQP协议限制，无法通过程序直接获取所有队列列表。</p>
                    <p>📌 请在下方输入框中输入要监控的队列名称：</p>
                    <div style="display: flex; gap: 10px; margin: 15px 0; flex-wrap: wrap;">
                        <input type="text" id="queueNameInput" placeholder="请输入队列名称" style="flex: 1; min-width: 200px;" />
                        <button class="btn btn-primary" onclick="addQueueToList()">➕ 添加队列</button>
                    </div>
                </div>
                <table id="queueTable">
                    <thead>
                        <tr>
                            <th>队列名称</th>
                            <th>消息数量</th>
                            <th>消费者数量</th>
                            <th>Virtual Host</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="queueTableBody">
                        <!-- 队列信息将在这里显示 -->
                    </tbody>
                </table>
            `;
        }

        // 添加队列到列表
        function addQueueToList() {
            const queueName = document.getElementById('queueNameInput').value.trim();
            if (!queueName) {
                alert('请输入队列名称');
                return;
            }

            // 检查是否已存在
            const existingRows = document.querySelectorAll('#queueTableBody tr');
            for (let i = 0; i < existingRows.length; i++) {
                if (existingRows[i].dataset.queue === queueName) {
                    alert('队列已存在');
                    return;
                }
            }

            // 添加新行
            const tbody = document.getElementById('queueTableBody');
            const virtualHost = document.getElementById('virtualHost').value || '/';
            const newRow = document.createElement('tr');
            newRow.dataset.queue = queueName;
            newRow.innerHTML = `
                <td class="queue-name" onclick="viewQueueDetails('${queueName}')">${queueName}</td>
                <td class="message-count" id="msg-count-${queueName}" onclick="viewMessages('${queueName}', '${virtualHost}')">加载中...</td>
                <td class="consumer-count" id="consumer-count-${queueName}">加载中...</td>
                <td>${escapeHtml(virtualHost)}</td>
                <td>
                    <button class="refresh-btn" onclick="refreshQueue('${queueName}', '${virtualHost}')">🔄 刷新</button>
                    <button class="remove-btn" onclick="removeQueue('${queueName}')">🗑️ 删除</button>
                </td>
            `;
            tbody.appendChild(newRow);

            // 获取队列信息
            fetchQueueInfo(queueName, virtualHost);
            
            // 清空输入框
            document.getElementById('queueNameInput').value = '';
        }

        // 获取队列信息
        function fetchQueueInfo(queueName, virtualHost) {
            let url = `/api/rabbitmq/queues/${queueName}`;
            if (virtualHost) {
                url += `?virtualHost=${encodeURIComponent(virtualHost)}`;
            }
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data && typeof data === 'object' && data.name) {
                        document.getElementById(`msg-count-${queueName}`).textContent = data.messageCount;
                        document.getElementById(`consumer-count-${queueName}`).textContent = data.consumerCount;
                    } else {
                        document.getElementById(`msg-count-${queueName}`).textContent = '获取失败';
                        document.getElementById(`consumer-count-${queueName}`).textContent = '获取失败';
                    }
                })
                .catch(error => {
                    console.error('Error fetching queue info:', error);
                    document.getElementById(`msg-count-${queueName}`).textContent = '错误';
                    document.getElementById(`consumer-count-${queueName}`).textContent = '错误';
                });
        }

        // 刷新单个队列信息
        function refreshQueue(queueName, virtualHost) {
            // 显示加载状态
            document.getElementById(`msg-count-${queueName}`).textContent = '加载中...';
            document.getElementById(`consumer-count-${queueName}`).textContent = '加载中...';
            
            // 重新获取队列信息
            fetchQueueInfo(queueName, virtualHost);
        }

        // 查看队列详细信息
        function viewQueueDetails(queueName) {
            // 这里可以扩展为显示更多队列详细信息
            alert(`队列名称: ${queueName}\n点击消息数量可以查看消息内容`);
        }

        // 查看队列消息内容
        function viewMessages(queueName, virtualHost) {
            // 显示模态框
            document.getElementById('modalQueueName').textContent = queueName;
            document.getElementById('messageContent').innerHTML = '<p class="loading">⏳ 正在加载消息...</p>';
            document.getElementById('messageModal').style.display = 'block';
            
            // 获取消息内容
            let url = `/api/rabbitmq/queues/${queueName}/contents?count=10`;
            if (virtualHost) {
                url += `&virtualHost=${encodeURIComponent(virtualHost)}`;
            }
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    const contentDiv = document.getElementById('messageContent');
                    if (data && data.length > 0) {
                        contentDiv.innerHTML = '';
                        data.forEach((message, index) => {
                            const messageDiv = document.createElement('div');
                            messageDiv.className = 'message-item';
                            messageDiv.innerHTML = `
                                <div class="message-content">
                                    <div class="message-header">📩 消息 #${index + 1}</div>
                                    <div>${escapeHtml(message)}</div>
                                </div>
                                <button class="delete-btn" onclick="deleteMessage('${queueName}', '${virtualHost}', ${index})">🗑️ 删除</button>
                            `;
                            contentDiv.appendChild(messageDiv);
                        });
                    } else {
                        contentDiv.innerHTML = '<div class="empty-state"><div class="empty-state-icon">📭</div><h3>该队列中没有消息</h3><p>或获取消息时出错</p></div>';
                    }
                })
                .catch(error => {
                    console.error('Error fetching messages:', error);
                    document.getElementById('messageContent').innerHTML = '<div class="error">❌ 获取消息时出错</div>';
                });
        }

        // 删除消息
        function deleteMessage(queueName, virtualHost, index) {
            if (confirm('是否删除本消息？')) {
                let url = `/api/rabbitmq/queues/${queueName}/message`;
                if (virtualHost) {
                    url += `?virtualHost=${encodeURIComponent(virtualHost)}`;
                }
                
                fetch(url, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('消息删除成功');
                        // 重新加载消息
                        viewMessages(queueName, virtualHost);
                        // 更新队列信息
                        fetchQueueInfo(queueName, virtualHost);
                    } else {
                        alert('消息删除失败: ' + (data.error || data.message));
                    }
                })
                .catch(error => {
                    console.error('Error deleting message:', error);
                    alert('删除消息时出错');
                });
            }
        }

        // 删除队列
        function removeQueue(queueName) {
            if (confirm(`确定要从监控列表中移除队列 "${queueName}" 吗？`)) {
                const row = document.querySelector(`tr[data-queue="${queueName}"]`);
                if (row) {
                    row.remove();
                }
            }
        }
        
        // 转义HTML特殊字符
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            
            return text.replace(/[&<>"']/g, function(m) { return map[m]; });
        }
    </script>
</body>
</html>